package com.chaosj.webmagic.handler;

import cn.hutool.core.text.StrFormatter;
import com.alibaba.fastjson.JSONObject;
import com.chaosj.webmagic.md.StorageApi;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.util.StringUtils;
import us.codecraft.webmagic.Page;

import java.util.ArrayList;
import java.util.List;

/**
 * @className: AbstractWriterHandler
 * @description:
 * @author: caoyangjie
 * @date: 2022/3/10
 **/
@Data
@Slf4j
public abstract class AbstractWriterHandler implements IWriterHandler {
    public static final String BASE_DIR = "baseDir";
    private JSONObject ctx;

    @Override
    public void process(Page page) {
        log(StrFormatter.format("获取 {} 文档成功!", page.getUrl().get()));
        String author = get(page, config().authorXPath(), defaultAuthor(page));
        String url = page.getUrl().toString();
        String title = get(page, config().titleXPath(), defaultTitle(page));
        List<String> contents = extractContent(page, title, url);
        appendCopyRight(contents, page, author, url);
        StorageApi.storageContent(ctx.getString(BASE_DIR), title, Joiner.on("\n").join(contents), title+".md");
    }

    @Override
    public boolean support(String uri) {
        return uri.startsWith(getSite().getDomain());
    }

    protected void log(String message){
        log.info( message );
        System.out.println(message);
    }

    protected List<String> extractContent(Page page,String title, String url){
        String contentValue = page.getHtml().xpath(config().contentXPath()).get();
        WriterMarkdownTools tools = new WriterMarkdownTools(ctx.getString(BASE_DIR), title, url);
        return tools.executeComment(Jsoup.parse(contentValue), new ArrayList<>(), null);
    }

    protected JSONObject getCtx(){
        return this.ctx;
    }

    @Override
    public <CTX> void initContext(CTX ctx) {
        this.ctx = (JSONObject) ctx;
    }

    protected String get(Page page, String xpath, String defaultValue) {
        String value = "";
        if(StringUtils.hasText(xpath)) {
            value = page.getHtml().xpath(xpath).get();
        }
        return StringUtils.hasText(value) ? value : defaultValue;
    }

    protected abstract String defaultAuthor(Page page);

    protected String defaultTitle(Page page) {
        List<String> titles = Splitter.on("/").splitToList(page.getUrl().get());
        return titles.get(titles.size()-1);
    }

    protected void appendCopyRight(List<String> contents, Page page, String author, String url) {
        contents.add(StrFormatter.format("作者: [{}](https://blog.luckycxy.com), [原文地址]({})", author, url));
    }
}
